from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST

from MirrorCore.models.Collection import Collection
from MirrorCore.models.Content import Article, Essay
from MirrorCore.permissions.permisssion import IsStaffOrReadOnly
from MirrorCore.serializers.ArticleSerializer import CollectionSerializer, ArticleSerializer
from MirrorCore.serializers.EssaySerializer import EssaySerializer
from MirrorCore.views.utils.Pagination import GetByPagination


class CollecitonResultsSetPagination(PageNumberPagination):
    page_size = 30

class CollectionViewSet(viewsets.ModelViewSet):

    serializer_class = CollectionSerializer
    pagination_class = CollecitonResultsSetPagination

    permission_classes = [IsStaffOrReadOnly]

    def get_queryset(self):
        if self.request.user.is_staff:
            return Collection.objects.all().order_by("-id")
        return Collection.objects.filter(is_active=True).order_by("-id")

    @action(detail=True,methods=['get'])
    def get_content(self, request, pk=None):
        """
        获得合集对应的文章内容
        :param request: type 请求内容列表 (article, default=essay)
        :param pk: badgeid
        :return:
        """

        type = request.GET.get('type', default='essay')
        page = request.GET.get('page', default='1')
        filter1 = { 'collection': pk }
        if self.request.user.is_staff is not True:
            filter1['is_active'] = True
        # 总数
        count = 0


        # TODO: 每篇文章请求作者时，产生重复数据库请求
        if type == 'article':
            list = Article.objects.filter(**filter1).order_by('-id')
            pglist, count = GetByPagination(list, 10, page)
            ser = ArticleSerializer(pglist, many=True)

        elif type == 'essay':
            list = Essay.objects.filter(**filter1).order_by('-id')
            pglist, count = GetByPagination(list, 10, page)
            ser = EssaySerializer(pglist, many=True)

        else:
            return Response({
                'type': "type不正确"
            }, status=HTTP_400_BAD_REQUEST)

        return Response({
            "count": count,
            "results": ser.data
        })